package org.chinasoft.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.chinasoft.aspect.ExceptionHandler;
import org.chinasoft.aspect.Log;
import org.chinasoft.entity.User;
import org.chinasoft.service.UserService;
import org.chinasoft.utils.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @PostMapping("/login")
    @ResponseBody
    @ExceptionHandler
    @Log(note = "登录系统")
    public ResultBean login(String username, String password, HttpSession session) {
        // 获取用户名密码
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // 获取当前用户主体
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        session.setAttribute("user", user);
        return new ResultBean().success();
    }

    @GetMapping("/logout")
    @ResponseBody
    @ExceptionHandler
    @Log(note = "注销系统")
    public ResultBean logout() {
        SecurityUtils.getSubject().logout();
        return new ResultBean().success();
    }
}
